package api

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type CourseController struct{}

// Index 课程列表
func (ctrl *CourseController) Index(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	level := c.Query("level")
	keyword := c.Query("keyword")

	var courses []models.Course
	var total int64

	db := config.DB.Model(&models.Course{}).Where("status = ?", 1)

	if level != "" {
		db = db.Where("level = ?", level)
	}
	if keyword != "" {
		db = db.Where("title LIKE ?", "%"+keyword+"%")
	}

	db.Count(&total)
	db.Order("sort desc, id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&courses)

	utils.Success(c, models.PageResponse{
		List:     courses,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// Detail 课程详情
func (ctrl *CourseController) Detail(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		utils.Error(c, "参数错误")
		return
	}

	var course models.Course
	if err := config.DB.Where("status = ?", 1).First(&course, id).Error; err != nil {
		utils.Error(c, "课程不存在")
		return
	}

	utils.Success(c, course)
}
